<template>
  <div>
    <div class="flex flexwrap">
      <el-input
        :placeholder="placeholder"
        size="small"
        v-model="keyword1"
        maxlength="50"
        show-word-limit
        :style="{ width: '100%', maxWidth: inputWidth }"
        @keyup.enter.native="handleAdd"
      >
        <template slot="append">
          <i class="el-icon-plus f-16 c_primary" @click="handleAdd"></i>
        </template>
      </el-input>
      <div class="ml-8 f-14">{{ keywordList.length }} / {{ listlength }}</div>
    </div>
    <div class="flex mt-8 flexwrap">
      <span
        v-for="(item, index) in keywordList"
        :key="index"
        class="mytag f-14"
      >
        {{ item }}
        <i class="el-icon-close commhover" @click="removeLable(index)"></i>
      </span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      keyword1: "",
      keywordList: [],
    };
  },
  props: {
    value: {
      type: Array,
      default: [],
    },
    inputWidth: {
      type: String,
      default: "580px",
    },
    listlength: {
      type: Number,
      default: 100,
    },
    placeholder:{
      type: String,
      default: '输入关键词，按回车添加',
    },
  },
  watch: {
    value: {
      handler(val) {
        this.keywordList = val
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    handleAdd() {
      if (this.keyword1) {
        if (this.keywordList.includes(this.keyword1)) {
          this.$message.warning("标签重复");
          return;
        }
        if (this.keywordList.length >= this.listlength) {
          this.$message.warning("最多只能添加" + listlength + "条");
          return;
        }
        this.keywordList.push(this.keyword1);
        this.keyword1 = "";
        this.$emit("input", this.keywordList);
      }
    },

    removeLable(index) {
      this.keywordList.splice(index, 1);
      this.$emit("input", this.keywordList);
    },
  },
};
</script>
<style lang="scss" scoped>
.mytag {
  position: relative;
  line-height: 24px;
  padding: 0 10px;
  font-weight: 400;
  color: #222;
  margin-right: 8px;
  background: rgba(0, 0, 0, 0.06);
  border-radius: 2px;
  margin-bottom: 8px;
  overflow: hidden;
  white-space: break-spaces;

  &::before {
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    width: 0;
    height: 0;
    border-color: #5976ef transparent transparent;
    border-style: solid;
    border-width: 10px 10px 0 0;
  }
}
</style>